package com.yong.automoguding.adapter;

import com.yong.automoguding.exception.MogudingException;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.CallAdapter;
import retrofit2.Response;
import retrofit2.Retrofit;

import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

/**
 *
 * 适配器
 * @author Hes
 */
public class CallToResponseEntityAdapterFactory extends CallAdapter.Factory {
    @Override
    public CallAdapter<?, ?> get(Type returnType, Annotation[] annotations, Retrofit retrofit) {
        return new CallAdapter<Object, Object>() {
            @Override
            public Type responseType() {
                return returnType;
            }

            @Override
            public Object adapt(Call<Object> call) {
                try {
                    Response<Object> execute = call.execute();
                    if (execute.isSuccessful()) {
                        return execute.body();
                    }
                    ResponseBody responseBody = execute.errorBody();
                    throw new MogudingException(responseBody == null ? "未知错误" : responseBody.string());
                } catch (Exception e) {
                    throw new MogudingException(e);
                }


            }
        };
    }
}
